import {
  createStore,
  applyMiddleware,
  Store,
  AnyAction,
  StoreCreator,
  StoreEnhancer,
} from "redux";
import reducers, { CombinedState } from "./reducers";

interface Ext {
  persist: string;
}
interface StateExt {
  hello: string;
}
type NewCombinedState = CombinedState & StateExt;

/**
 * createStore方法的四个泛型
 * CombinedState 合并后的状态树
 * AnyAction 可以向仓库派发的动作
 * Ext
 * StateExt
 */
let store: Store<NewCombinedState, AnyAction> & Ext = createStore<
  CombinedState,
  AnyAction,
  Ext,
  StateExt
>(reducers, storeEnhancer<Ext, StateExt>());
//store.dispatch store.getState store.replaceReducer store.subscribe
store.getState().counter;
store.getState().router;
store.getState().hello;
console.log(store.persist);
console.log(store.getState().router);
//storeCreator就是创建store的那个函数 createStore
let storeCreator: StoreCreator = createStore;
// enhancer?: StoreEnhancer<Ext, StateExt>
let enhancer: StoreEnhancer = applyMiddleware;

//StoreEnhancerStoreCreator 增强版的createStore
//StoreEnhancer  applyMiddleware

export default store;

function storeEnhancer<Ext, StateExt>() {
  return (createStore: any) => (reducer: any, enhancer: any) => {
    var store = createStore(reducer, enhancer);
    return {
      ...store,
      persist: "persist",
    };
  };
}
